package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 全文检索
     *
     * @param paramMap 查询参数
     * @return
     * @throws Exception
     */
    @Override
    public Map search(Map<String, String> paramMap) throws Exception {
        // 返回结果集合
        Map<String, Object> resultMap = new HashMap<>();
        // 构建查询
        if (paramMap != null && !paramMap.equals("")) {
            // 封装查询条件到查询条件封装对象
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

            // 按照关键字查询
            if (!StringUtils.isEmpty(paramMap.get("keywords"))) {
                boolQuery.must(QueryBuilders.matchQuery("name", paramMap.get("keywords")).operator(Operator.AND));
            }

            // 按照品牌过滤查询
            if (!StringUtils.isEmpty(paramMap.get("brand"))) {
                boolQuery.filter(QueryBuilders.termQuery("brandName", paramMap.get("brand")));
            }

            // 按照规格过滤查询
            for (String key : paramMap.keySet()) {
                if (key.startsWith("spec_")) {
                    String value = paramMap.get(key).replace("%2B", "+");
                    // spec_网络制式 -> 网络制式
                    boolQuery.filter(QueryBuilders.termQuery(("specMap." + key.substring(5) + ".keyword"), value));
                }
            }

            // 按照价格进行区间过滤查询
            if (!StringUtils.isEmpty(paramMap.get("price"))) {
                String[] prices = paramMap.get("price").split("-");
                // 0-500 500-1000
                if (prices.length == 2) {
                    // lte 小于等于
                    boolQuery.filter(QueryBuilders.rangeQuery("price").lte(prices[1]));
                }
                // gte 大于等于
                boolQuery.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));
            }

            // 原生搜索实现类
            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            nativeSearchQueryBuilder.withQuery(boolQuery);

            // 品牌聚合（分组）查询
            String skuBrand = "skuBrand";
            // 聚合
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuBrand).field("brandName"));

            // 按照规格进行聚合查询
            String skuSpec = "skuSpec";
            nativeSearchQueryBuilder.addAggregation(AggregationBuilders.terms(skuSpec).field("spec.keyword"));

            // 开启分页查询
            String pageNum = paramMap.get("pageNum");  // 当前页
            String pageSize = paramMap.get("pageSize");// 每页显示条数
            if (StringUtils.isEmpty(pageNum)) {
                pageNum = "1";
            }
            if (StringUtils.isEmpty(pageSize)) {
                pageSize = "30";
            }
            /**
             * 设置分页
             * 参数1：当前页，从0开始算，所以需要减1操作
             * 参数2：每页显示条数
             */
            nativeSearchQueryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum) - 1, Integer.parseInt(pageSize)));

            // 按照相关字段进行排序查询
            // 1.当前域 2.当前的排序操作（升序asc 降序desc）
            if (!StringUtils.isEmpty(paramMap.get("sortField")) && !StringUtils.isEmpty(paramMap.get("sortRule"))) {
                if ("ASC".equals(paramMap.get("sortRule"))) {
                    // 升序排序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((paramMap.get("sortField"))).order(SortOrder.ASC));
                } else {
                    // 降序排序
                    nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort((paramMap.get("sortField"))).order(SortOrder.DESC));
                }
            }

            // 设置高亮域及高亮样式
            HighlightBuilder.Field field = new HighlightBuilder.Field("name")  // 对name域高亮
                    .preTags("<span style='color:red'>")    // 高亮样式前缀
                    .postTags("</span>");   // 高亮样式的后缀
            nativeSearchQueryBuilder.withHighlightFields(field);

            /*
             * 第一个参数：条件构建对象
             * 第二个参数：查询操作实体类
             * 第三个参数：查询结果操作对象
             */
            AggregatedPage<SkuInfo> resultInfo = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    // 查询结果相关操作
                    List<T> list = new ArrayList<>();
                    SearchHits hits = searchResponse.getHits();
                    if (hits != null) {
                        // 有查询结果
                        for (SearchHit hit : hits) {
                            SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);

                            //
                            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                            if (highlightFields != null && highlightFields.size() > 0) {
                                // 替换数据：高亮样式
                                skuInfo.setName(highlightFields.get("name").getFragments()[0].toString());
                            }

                            list.add((T) skuInfo);
                        }
                    }
                    return new AggregatedPageImpl<>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                }
            });

            // 总条数
            resultMap.put("total", resultInfo.getTotalElements());
            // 总页数
            resultMap.put("totalPages", resultInfo.getTotalPages());
            // 查询结果集合
            resultMap.put("rows", resultInfo.getContent());

            // 封装品牌的分组结果
            StringTerms brandTerms = (StringTerms) resultInfo.getAggregation(skuBrand);
            List<String> brandList = brandTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("brandList", brandList);

            // 封装规格分组结果
            StringTerms specTerms = (StringTerms) resultInfo.getAggregation(skuSpec);
            List<String> specList = specTerms.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("specList", this.formatSpec(specList));

            // 当前页
            resultMap.put("pageNum", pageNum);
            return resultMap;
        }
        return null;
    }

    /**
     *  原有数据：
     *         "{'颜色': '蓝色', '版本': '6GB+128GB'}",
     *         "{'颜色': '黑色', '版本': '6GB+128GB'}",
     *         "{'颜色': '黑色', '版本': '4GB+64GB'}",
     *         "{'颜色': '蓝色', '版本': '4GB+64GB'}",
     *         "{'颜色': '蓝色', '版本': '6GB+64GB'}",
     *         "{'颜色': '黑色', '版本': '6GB+64GB'}",
     *         "{'颜色': '黑色'}",
     *         "{'颜色': '蓝色'}",
     *         "{'颜色': '金色', '版本': '4GB+64GB'}",
     *         "{'颜色': '粉色', '版本': '6GB+128GB'}"
     *  处理后的数据：
     *          {
     *              颜色：{蓝色，黑色，金色，粉色}.
     *              版本：{6+128GB,4+64GB,6+64GB}
     *          }
     *
     */
    /**
     * 实现上述数据格式转换
     * @param specList
     * @return
     */
    public Map<String,Set<String>> formatSpec(List<String> specList){
        Map<String,Set<String>> resultMap = new HashMap<>();
        if (specList != null && specList.size() > 0){
            for (String specJsonString : specList) {
                // 将json转换为map
                Map<String,String> specMap = JSON.parseObject(specJsonString,Map.class);
                for (String specKey : specMap.keySet()) {
                    // value的集合key
                    Set<String> specSet = resultMap.get(specKey);
                    if (specSet == null){
                        specSet = new HashSet<String>();
                    }
                    // 将规格的值放入set中
                    specSet.add(specMap.get(specKey));
                    // 将set放入map中
                    resultMap.put(specKey,specSet);
                }

            }
        }
        return resultMap;
    }
}
